package com.aerors.DataProcess;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class TestCesiumLayerJSON {

	public static void main(String[] args) {
		String baseDir = "C:\\data\\dem\\ctt2";
		String name = "testCTT";
		String bounds = "98.99985949772001,32.99588058827454,100.0117010112965,34.00420469218622";
		
		TestCesiumLayerJSON tt = new TestCesiumLayerJSON();
		tt.generateLayerJSON(baseDir, name, bounds);
	}
	
	public void generateLayerJSON(String baseDir,String name,String bounds) {
		JSONObject layerJSON = new JSONObject();

		layerJSON.put("tilejson","2.1.0");
		layerJSON.put("name",name);
		layerJSON.put("description","");
		layerJSON.put("version","1.1.0");
		layerJSON.put("format","quantized-mesh-1.0");
		layerJSON.put("attribution","");
		layerJSON.put("schema","tms");
		
		JSONArray extJsonArray = new JSONArray();
		extJsonArray.add("octvertexnormals");
		layerJSON.put("extensions",extJsonArray);
		
		layerJSON.put("tiles","{z}/{x}/{y}.terrain?v={version}");
		layerJSON.put("projection","EPSG:4326");
		
		JSONArray boundJsonArray = new JSONArray();
		String[] boundArray = bounds.split(",");
		boundJsonArray.add(boundArray[0]);
		boundJsonArray.add(boundArray[1]);
		boundJsonArray.add(boundArray[2]);
		boundJsonArray.add(boundArray[3]);
		layerJSON.put("bounds",boundJsonArray);
		
		JSONArray avaArray = new JSONArray();
		for (int i = 0; i < 19; i++) {
			File zFolder = new File(baseDir + File.separator + i);
			JSONArray tempArray = new JSONArray();
			if (zFolder.exists()) {
				JSONObject tempAva = new JSONObject();

				List<File> xlist = Arrays.asList(zFolder.listFiles());
				int startX = Integer.parseInt(xlist.get(0).getName());
				int endX = Integer.parseInt(xlist.get(xlist.size() - 1).getName());

				List<File> ylist = Arrays.asList(xlist.get(0).listFiles());
				int startY = Integer.parseInt(ylist.get(0).getName().replace(".terrain", ""));
				int endY = Integer.parseInt(ylist.get(0).getName().replace(".terrain", ""));

				tempAva.put("startX", startX);
				tempAva.put("startY", startY);
				tempAva.put("endX", endX);
				tempAva.put("endY", endY);

				tempArray.add(tempAva);
			}
			avaArray.add(tempArray);
		}
		layerJSON.put("available",avaArray);
		
		File f = new File(baseDir + File.separator + "layer.json");
		FileOutputStream fous = null;
		try {
			fous = new FileOutputStream(f);
			fous.write(layerJSON.toString().getBytes());
			fous.flush();
			fous.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
